from flaskAdminApp import app, db
from flask import jsonify, request, json
from flask_httpauth import HTTPTokenAuth
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired
from flaskAdminApp.abnormal.errorClass import Success, TokenError, ServerError, UserError

from flaskAdminApp.tools.tools import DATADB as d

auth = HTTPTokenAuth(scheme='JWT')
from flaskAdminApp.models.datadb import sys_user as sysuser


class AdminController:
    # 添加管理员用户
    def addUsers(**self):
        user_name = self['user_name']
        nick_name = self['nick_name']
        email = self['email']
        phonenumber = self['phonenumber']
        password = self['password']
        if sysuser.query.filter(sysuser.phonenumber == phonenumber).count() > 0:
            data = dict(
                userInfo=d.phoneGetuserInfo(phonenumber),
                token=AdminController.getUserToken(phonenumber=phonenumber)
            )
            raise Success(data=data)
        else:
            obj = sysuser(user_name=user_name, nick_name=nick_name, email=email, phonenumber=phonenumber,password=password)
            db.session.add(obj)
            db.session.commit()
            raise Success(msg='注册成功')

    # 获取用户信息
    def userInfo(**self):
        userinfo = d.phoneGetuserInfo(self['phonenumber'])
        if userinfo:
            data = dict(
                userinfo
            )
            raise Success(data=data)
        else:
            raise ServerError()

    # 登录
    def Login(**self):
        phonenumber = self['phonenumber']
        password = self['password']
        num = sysuser.query.filter_by(phonenumber=phonenumber).count()
        obj = sysuser.query.filter_by(phonenumber=phonenumber).first()

        if num>0:
            if obj.check_password(password):
                data = dict(
                userInfo=obj.to_json(),
                token=obj.create_token(obj.user_id)
                )
                raise Success(data=data)
            else:
                raise UserError()
        else:
            raise UserError()

    # 获取token
    def getUserToken(**self):

        userinfo = sysuser.query.filter_by(phonenumber=self['phonenumber']).first()
        return userinfo.create_token(userinfo.user_id)

    # token换取用户信息
    def tokenGetUserInfo(**self):
        token = self['token']
        s = Serializer(app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
            user = sysuser.query.filter_by(user_id=data['id']).first()
            data = jsonify({
                'code': 200,
                'data': user.to_json()
            })
            raise Success(data=data)
        except:
            raise TokenError()
        return 'success'
